home *** CD-ROM | disk | FTP | other *** search
/ Collection of Internet / Collection of Internet.iso / faq / comp / c_faq / abridged next >
Internet Message Format  |  1994-04-15  |  40KB

  1. Path: bloom-beacon.mit.edu!hookup!nntp.cs.ubc.ca!cyber2.cyberstore.ca!nwnexus!ole!rwing!eskimo!scs
  2. From: scs@eskimo.com (Steve Summit)
  3. Newsgroups: comp.lang.c,comp.answers,news.answers
  4. Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)
  5. Message-ID: <1994Apr15.0300.scs.0001@eskimo.com>
  6. Date: 15 Apr 94 10:00:24 GMT
  7. Expires: Tue, 3 May 1994 00:00:00 GMT
  8. Sender: scs@eskimo.com (Steve Summit)
  9. Reply-To: scs@eskimo.com
  10. Followup-To: poster
  11. Organization: none, at the moment
  12. Lines: 1252
  13. Approved: news-answers-request@MIT.Edu
  14. Supersedes: <1994Apr01.0306.scs.0003@eskimo.com>
  15. X-Archive-Name: C-faq/abridged
  16. X-Last-Modified: March 1, 1994
  17. Xref: bloom-beacon.mit.edu comp.lang.c:38589 comp.answers:4922 news.answers:18103
  18.  
  19. Archive-name: C-faq/abridged
  20. Comp-lang-c-archive-name: C-FAQ-list.abridged
  21.  
  22. [Last modified March 1, 1994 by scs.]
  23.  
  24. This article contains minimal answers to the comp.lang.c frequently-
  25. asked questions list.  Please see the long version (posted on the
  26. first of each month, or see question 17.33 for availability) for more
  27. detailed explanations and references.
  28.  
  29.  
  30. Section 1. Null Pointers
  31.  
  32. 1.1:    What is this infamous null pointer, anyway?
  33.  
  34. A:    For each pointer type, there is a special value -- the "null
  35.     pointer" -- which is distinguishable from all other pointer
  36.     values and which is not the address of any object or function.
  37.  
  38. 1.2:    How do I "get" a null pointer in my programs?
  39.  
  40. A:    A constant 0 in a pointer context is converted into a null
  41.     pointer at compile time.  A "pointer context" is an
  42.     initialization, assignment, or comparison with one side a
  43.     variable or expression of pointer type, and (in ANSI standard C)
  44.     a function argument which has a prototype in scope declaring a
  45.     certain parameter as being of pointer type.  In other contexts
  46.     (function arguments without prototypes, or in the variable part
  47.     of variadic function calls) a constant 0 with an appropriate
  48.     explicit cast is required.
  49.  
  50. 1.3:    What is NULL and how is it #defined?
  51.  
  52. A:    NULL is simply a preprocessor macro, #defined as 0 (or
  53.     (void *)0), which is used (as a stylistic convention, in
  54.     preference to unadorned 0's) to generate null pointers,
  55.  
  56. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  57.     bit pattern as the internal representation of a null pointer?
  58.  
  59. A:    The same as any other machine: as 0 (or (void *)0).  (The
  60.     compiler makes the translation, upon seeing a 0, not the
  61.     preprocessor.)
  62.  
  63. 1.5:    If NULL were defined as "(char *)0," wouldn't that make function
  64.     calls which pass an uncast NULL work?
  65.  
  66. A:    Not in general.  The problem is that there are machines which
  67.     use different internal representations for pointers to different
  68.     types of data.  A cast is still required to tell the compiler
  69.     which kind of null pointer is required, since it may be
  70.     different from (char *)0.
  71.  
  72. 1.6:    I use the preprocessor macro "#define Nullptr(type) (type *)0"
  73.     to help me build null pointers of the correct type.
  74.  
  75. A:    This trick, though valid, does not buy much.
  76.  
  77. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  78.     null pointers valid?  What if the internal representation for
  79.     null pointers is nonzero?
  80.  
  81. A:    The construction "if(p)" works, regardless of the internal
  82.     representation of null pointers, because the compiler
  83.     essentially rewrites it as "if(p != 0)" and goes on to convert 0
  84.     into the correct null pointer.
  85.  
  86. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  87.  
  88. A:    Either; the distinction is entirely stylistic.
  89.  
  90. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  91.     the value of NULL changes, perhaps on a machine with nonzero
  92.     null pointers?
  93.  
  94. A:    No.  NULL is, and will always be, 0.
  95.  
  96. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  97.     is not?
  98.  
  99. A:    A "null pointer" is a language concept whose particular internal
  100.     value does not matter.  A null pointer is requested in source
  101.     code with the character "0".  "NULL" is a preprocessor macro,
  102.     which is always #defined as 0 (or (void *)0).
  103.  
  104. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  105.     do these questions come up so often?
  106.  
  107. A:    The fact that null pointers are represented both in source code,
  108.     and internally to most machines, as zero invites unwarranted
  109.     assumptions.  The use of a preprocessor macro (NULL) suggests
  110.     that the value might change later, or on some weird machine.
  111.  
  112. 1.12:    I'm still confused.  I just can't understand all this null
  113.     pointer stuff.
  114.  
  115. A:    A simple rule is, "Always use `0' or `NULL' for null pointers,
  116.     and always cast them when they are used as arguments in function
  117.     calls."
  118.  
  119. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  120.     be easier simply to require them to be represented internally by
  121.     zeroes?
  122.  
  123. A:    Such a requirement would accomplish little.
  124.  
  125. 1.14:    Seriously, have any actual machines really used nonzero null
  126.     pointers?
  127.  
  128. A:    Machines manufactured by Prime, Honeywell-Bull, and CDC, as well
  129.     as Symbolics Lisp Machines, have done so.
  130.  
  131. 1.15:    What does a run-time "null pointer assignment" error mean?
  132.  
  133. A:    It means that you've written through a null pointer.
  134.  
  135.  
  136. Section 2. Arrays and Pointers
  137.  
  138. 2.1:    I had the definition char a[6] in one source file, and in
  139.     another I declared extern char *a.  Why didn't it work?
  140.  
  141. A:    The declaration extern char *a simply does not match the actual
  142.     definition.  Use extern char a[].
  143.  
  144. 2.2:    But I heard that char a[] was identical to char *a.
  145.  
  146. A:    Not at all.  Arrays are not pointers.  A reference like x[3]
  147.     generates different code depending on whether x is an array or a
  148.     pointer.
  149.  
  150. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  151.     C?
  152.  
  153. A:    An lvalue of type array-of-T which appears in an expression
  154.     decays into a pointer to its first element; the type of the
  155.     resultant pointer is pointer-to-T.  So for an array a and
  156.     pointer p, you can say "p = a;" and then p[3] and a[3] will
  157.     access the same element.
  158.  
  159. 2.4:    Why are array and pointer declarations interchangeable as
  160.     function formal parameters?
  161.  
  162. A:    Since functions can never receive arrays as parameters, any
  163.     parameter declarations which "look like" arrays are treated by
  164.     the compiler as if they were pointers.
  165.  
  166. 2.5:    How can an array be an lvalue, if you can't assign to it?
  167.  
  168. A:    An array is not a "modifiable lvalue."
  169.  
  170. 2.6:    Why doesn't sizeof properly report the size of an array which is
  171.     a parameter to a function?
  172.  
  173. A:    The sizeof operator reports the size of the pointer parameter
  174.     which the function actually receives.
  175.  
  176. 2.7:    Someone explained to me that arrays were really just constant
  177.     pointers.
  178.  
  179. A:    An array name is "constant" in that it cannot be assigned to,
  180.     but an array is _not_ a pointer.
  181.  
  182. 2.8:    What is the real difference between arrays and pointers?
  183.  
  184. A:    Arrays automatically allocate space but are fixed (in size and
  185.     location); pointers are dynamic.
  186.  
  187. 2.9:    I came across some "joke" code containing the "expression"
  188.     5["abcdef"] .  How can this be legal C?
  189.  
  190. A:    Yes, array subscripting is commutative in C.  The array
  191.     subscripting operation a[e] is defined as being identical to
  192.     *((a)+(e)).
  193.  
  194. 2.10:    My compiler complained when I passed a two-dimensional array to
  195.     a routine expecting a pointer to a pointer.
  196.  
  197. A:    The rule by which arrays decay into pointers is not applied
  198.     recursively.  An array of arrays (i.e. a two-dimensional array
  199.     in C) decays into a pointer to an array, not a pointer to a
  200.     pointer.
  201.  
  202. 2.11:    How do I write functions which accept 2-dimensional arrays when
  203.     the "width" is not known at compile time?
  204.  
  205. A:    It's not particularly easy.
  206.  
  207. 2.12:    How do I declare a pointer to an array?
  208.  
  209. A:    Usually, you don't want to.  Consider using a pointer to one of
  210.     the array's elements instead.
  211.  
  212. 2.13:    What's the difference between array and &array?
  213.  
  214. A:    Under ANSI/ISO Standard C, &array yields a pointer to the entire
  215.     array.  An unadorned reference to an array yields a pointer to
  216.     the array's first element.
  217.  
  218. 2.14:    How can I dynamically allocate a multidimensional array?
  219.  
  220. A:    It is usually best to allocate an array of pointers, and then
  221.     initialize each pointer to a dynamically-allocated "row."  See
  222.     the full list for code samples.
  223.  
  224. 2.15:    How can I use statically- and dynamically-allocated
  225.     multidimensional arrays interchangeably when passing them to
  226.     functions?
  227.  
  228. A:    There is no single perfect method, but see the full list for
  229.     some ideas.
  230.  
  231. 2.16:    Can I simulate a non-0-based array with a pointer?
  232.  
  233. A:    Not if the pointer points outside of the block of memory it is
  234.     intended to access.
  235.  
  236. 2.17:    I passed a pointer to a function which initialized it, but the
  237.     pointer in the caller was unchanged.
  238.  
  239. A:    The called function probably altered only the passed copy of the
  240.     pointer.
  241.  
  242. 2.18:    I have a char * pointer that happens to point to some ints, and
  243.     I want to step it over them.  Why doesn't "((int *)p)++;" work?
  244.  
  245. A:    In C, a cast operator is a conversion operator, and by
  246.     definition it yields an rvalue, which cannot be assigned to, or
  247.     incremented with ++.
  248.  
  249. 2.19:    Can I use a void ** pointer to pass a generic pointer to a
  250.     function by reference?
  251.  
  252. A:    Not portably.
  253.  
  254.  
  255. Section 3. Memory Allocation
  256.  
  257. 3.1:    Why doesn't the code "char *answer; gets(answer);" work?
  258.  
  259. A:    The pointer variable "answer" has not been set to point to any
  260.     valid storage.  The simplest way to correct this fragment is to
  261.     use a local array, instead of a pointer.
  262.  
  263. 3.2:    I can't get strcat to work.  I tried "char *s1 = "Hello, ",
  264.     *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange
  265.     results.
  266.  
  267. A:    Again, the problem is that space for the concatenated result is
  268.     not properly allocated.
  269.  
  270. 3.3:    But the man page for strcat says that it takes two char *'s as
  271.     arguments.  How am I supposed to know to allocate things?
  272.  
  273. A:    In general, when using pointers you _always_ have to consider
  274.     memory allocation, at least to make sure that the compiler is
  275.     doing it for you.
  276.  
  277. 3.4:    I have a function that is supposed to return a string, but when
  278.     it returns to its caller, the returned string is garbage.
  279.  
  280. A:    Make sure that the memory to which the function returns a
  281.     pointer is correctly (i.e. not locally) allocated.
  282.  
  283. 3.5:    Why does some code carefully cast the values returned by malloc
  284.     to the pointer type being allocated?
  285.  
  286. A:    Before ANSI/ISO C, these casts were required to silence certain
  287.     warnings.
  288.  
  289. 3.6:    You can't use dynamically-allocated memory after you free it,
  290.     can you?
  291.  
  292. A:    No.  Some early documentation implied otherwise, but the claim
  293.     is no longer valid.
  294.  
  295. 3.7:    How does free() know how many bytes to free?
  296.  
  297. A:    The malloc/free package remembers the size of each block it
  298.     allocates and returns.
  299.  
  300. 3.8:    So can I query the malloc package to find out how big an
  301.     allocated block is?
  302.  
  303. A:    Not portably.
  304.  
  305. 3.9:    When I free a dynamically-allocated structure containing
  306.     pointers, do I have to free each subsidiary pointer first?
  307.  
  308. A:    Yes.
  309.  
  310. 3.10:    Why doesn't my program's memory usage go down when I free
  311.     memory?
  312.  
  313. A:    Most implementations of malloc/free do not return freed memory
  314.     to the operating system.
  315.  
  316. 3.11:    Must I free allocated memory before the program exits?
  317.  
  318. A:    You shouldn't have to.
  319.  
  320. 3.12:    Is it legal to pass a null pointer as the first argument to
  321.     realloc()?
  322.  
  323. A:    ANSI C sanctions this usage, but several earlier implementations
  324.     do not support it.
  325.  
  326. 3.13:    Is it safe to use calloc's zero-fill guarantee for pointer and
  327.     floating-point values?
  328.  
  329. A:    No.
  330.  
  331. 3.14:    What is alloca and why is its use discouraged?
  332.  
  333. A:    alloca allocates memory which is automatically freed when the
  334.     function which called alloca returns.  alloca cannot be written
  335.     portably, is difficult to implement on machines without a stack,
  336.     and fails under certain conditions if implemented simply.
  337.  
  338.  
  339. Section 4. Expressions
  340.  
  341. 4.1:    Why doesn't the code "a[i] = i++;" work?
  342.  
  343. A:    The variable i is both referenced and modified in the same
  344.     expression.
  345.  
  346. 4.2:    Under my compiler, the code "int i = 7;
  347.     printf("%d\n", i++ * i++);" prints 49.  Regardless of the order
  348.     of evaluation, shouldn't it print 56?
  349.  
  350. A:    The operations implied by the postincrement and postdecrement
  351.     operators ++ and -- are performed at some time after the
  352.     operand's former values are yielded and before the end of the
  353.     expression, but not necessarily immediately after, or before
  354.     other parts of the expression are evaluated.
  355.  
  356. 4.3:    How could the code "int i = 2; i = i++;" ever give 4?
  357.  
  358. A:    Undefined behavior means _anything_ can happen.
  359.  
  360. 4.4:    I just tried some allegedly-undefined code on an ANSI-conforming
  361.     compiler, and got the results I expected.
  362.  
  363. A:    A compiler may do anything it likes when faced with undefined
  364.     behavior, including doing what you expect.
  365.  
  366. 4.5:    Don't precedence and parentheses dictate order of evaluation?
  367.  
  368. A:    Operator precedence and explicit parentheses impose only a
  369.     partial ordering on the evaluation of an expression, which does
  370.     not generally include the order of side effects.
  371.  
  372. 4.6:    But what about the &&, ||, and comma operators?
  373.  
  374. A:    There is a special exception for those operators, (as well as
  375.     ?: ); left-to-right evaluation is guaranteed.
  376.  
  377. 4.7:    If I'm not using the value of the expression, should I use i++
  378.     or ++i to increment a variable?
  379.  
  380. A:    Since the two forms differ only in the value yielded, they are
  381.     entirely equivalent when only their side effect is needed.
  382.  
  383. 4.8:    Why doesn't the code "int a = 1000, b = 1000;
  384.     long int c = a * b;" work?
  385.  
  386. A:    You must manually cast one of the operands to (long).
  387.  
  388.  
  389. Section 5. ANSI C
  390.  
  391. 5.1:    What is the "ANSI C Standard?"
  392.  
  393. A:    In 1983, the American National Standards Institute (ANSI)
  394.     commissioned a committee to standardize the C language.  Their
  395.     work was ratified as ANS X3.159-1989, and has since been adopted
  396.     as ISO/IEC 9899:1990.
  397.  
  398. 5.2:    How can I get a copy of the Standard?
  399.  
  400. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  401.     are available from ANSI in New York, or from Global Engineering
  402.     Documents in Irvine, CA.  See the unabridged list for addresses.
  403.  
  404. 5.3:    Does anyone have a tool for converting old-style C programs to
  405.     ANSI C, or for automatically generating prototypes?
  406.  
  407. A:    See the full list for details.
  408.  
  409. 5.4:    How do I keep the ANSI "stringizing" preprocessing operator from
  410.     stringizing the macro's name rather than its value?
  411.  
  412. A:    You must use a two-step #definition to force the macro to be
  413.     expanded as well as stringized.
  414.  
  415. 5.5:    Why can't I use const values in initializers and array
  416.     dimensions?
  417.  
  418. A:    The value of a const-qualified object is _not_ a constant
  419.     expression in the full sense of the term.
  420.  
  421. 5.6:    What's the difference between "char const *p" and
  422.     "char * const p"?
  423.  
  424. A:    The former is a pointer to a constant character; the latter is a
  425.     constant pointer to a character.
  426.  
  427. 5.7:    Why can't I pass a char ** to a function which expects a
  428.     const char **?
  429.  
  430. A:    The rule which permits slight mismatches in qualified pointer
  431.     assignments is not applied recursively.
  432.  
  433. 5.8:    My ANSI compiler complains about a mismatch when it sees
  434.  
  435.         extern int func(float);
  436.  
  437.         int func(x)
  438.         float x;
  439.         {...
  440.  
  441. A:    You have mixed the new-style prototype declaration
  442.     "extern int func(float);" with the old-style definition
  443.     "int func(x) float x;".  "Narrow" types are treated differently
  444.     according to which syntax is used.  This problem can be fixed by
  445.     avoiding narrow types, or by using either new-style (prototype)
  446.     or old-style syntax consistently.
  447.  
  448. 5.9:    Can you mix old-style and new-style function syntax?
  449.  
  450. A:    Doing so is currently perfectly legal.
  451.  
  452. 5.10:    Why does the declaration "extern f(struct x {int s;} *p);" give
  453.     me a warning message?
  454.  
  455. A:    A struct declared only within a prototype cannot be compatible
  456.     with other structs declared in the same source file.
  457.  
  458. 5.11:    I'm getting strange syntax errors inside code which I've
  459.     #ifdeffed out.
  460.  
  461. A:    Under ANSI C, #ifdeffed-out text must still consist of "valid
  462.     preprocessing tokens."  This means that there must be no
  463.     unterminated comments or quotes (i.e. no single apostrophes),
  464.     and no newlines inside quotes.
  465.  
  466. 5.12:    Can I declare main as void, to shut off these annoying "main
  467.     returns no value" messages?
  468.  
  469. A:    No.
  470.  
  471. 5.13:    Is exit(status) truly equivalent to returning status from main?
  472.  
  473. A:    Essentially.
  474.  
  475. 5.14:    Why does the ANSI Standard not guarantee more than six monocase
  476.     characters of external identifier significance?
  477.  
  478. A:    The problem is older linkers which cannot be forced (by mere
  479.     words in a Standard) to upgrade.
  480.  
  481. 5.15:    What is the difference between memcpy and memmove?
  482.  
  483. A:    memmove offers guaranteed behavior if the source and destination
  484.     arguments overlap.
  485.  
  486. 5.16:    My compiler is rejecting the simplest possible test programs,
  487.     with all kinds of syntax errors.
  488.  
  489. A:    Perhaps it is a pre-ANSI compiler.
  490.  
  491. 5.17:    Why are some ANSI/ISO Standard library routines showing up as
  492.     undefined, even though I've got an ANSI compiler?
  493.  
  494. A:    Perhaps you don't have ANSI-compatible headers and libraries.
  495.  
  496. 5.18:    Why won't frobozz-cc, which claims to be ANSI compliant, accept
  497.     this code?
  498.  
  499. A:    Are you sure that the code being rejected doesn't rely on some
  500.     non-Standard extension?
  501.  
  502. 5.19:    Why can't I perform arithmetic on a void * pointer?
  503.  
  504. A:    The compiler doesn't know the size of the pointed-to objects.
  505.  
  506. 5.20:    Is char a[3] = "abc"; legal?
  507.  
  508. A:    Yes, in ANSI C.
  509.  
  510. 5.21:    What are #pragmas and what are they good for?
  511.  
  512. A:    The #pragma directive provides a single, well-defined "escape
  513.     hatch" which can be used for extensions.
  514.  
  515. 5.22:    What does #pragma once mean?
  516.  
  517. A:    It is an extension implemented by some preprocessors to help
  518.     make header files idempotent.
  519.  
  520. 5.23:    What's the difference between implementation-defined,
  521.     unspecified, and undefined behavior?
  522.  
  523. A:    If you're writing portable code, ignore the distinctions.
  524.     Otherwise, see the full list.
  525.  
  526.  
  527. Section 6. C Preprocessor
  528.  
  529. 6.1:    How can I write a generic macro to swap two values?
  530.  
  531. A:    There is no good answer to this question.  The best all-around
  532.     solution is probably to forget about using a macro.
  533.  
  534. 6.2:    I have some old code that tries to construct identifiers with a
  535.     macro like "#define Paste(a, b) a/**/b ", but it doesn't work
  536.     any more.
  537.  
  538. A:    Try the ANSI token-pasting operator ##.
  539.  
  540. 6.3:    What's the best way to write a multi-statement cpp macro?
  541.  
  542. A:    #define Func() do {stmt1; stmt2; ... } while(0)  /* (no trailing ;) */
  543.  
  544. 6.4:    Is it acceptable for one header file to #include another?
  545.  
  546. A:    It's a question of style, and thus receives considerable debate.
  547.  
  548. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  549.  
  550. A:    No.
  551.  
  552. 6.6:    How can I use a preprocessor #if expression to detect
  553.     endianness?
  554.  
  555. A:    You probably can't.
  556.  
  557. 6.7:    I've got this tricky processing I want to do at compile time and
  558.     I can't figure out a way to get cpp to do it.
  559.  
  560. A:    Consider writing your own little special-purpose preprocessing
  561.     tool, instead.
  562.  
  563. 6.8:    How can I preprocess some code to remove selected conditional
  564.     compilations, without preprocessing everything?
  565.  
  566. A:    Look for a program called unifdef, rmifdef, or scpp.
  567.  
  568. 6.9:    How can I list all of the pre#defined identifiers?
  569.  
  570. A:    Try extracting printable strings from the compiler or
  571.     preprocessor executable.
  572.  
  573. 6.10:    How can I write a cpp macro which takes a variable number of
  574.     arguments?
  575.  
  576. A:    Here is one popular trick.  Note that the parentheses around
  577.     printf's argument list are in the macro call, not the
  578.     definition.
  579.  
  580.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  581.  
  582.         if(n != 0) DEBUG(("n is %d\n", n));
  583.  
  584.  
  585. Section 7. Variable-Length Argument Lists
  586.  
  587. 7.1:    How can I write a function that takes a variable number of
  588.     arguments?
  589.  
  590. A:    Use the <stdarg.h> (or older <varargs.h>) header.
  591.  
  592. 7.2:    How can I write a function that takes a format string and a
  593.     variable number of arguments, like printf, and passes them to
  594.     printf to do most of the work?
  595.  
  596. A:    Use vprintf, vfprintf, or vsprintf.
  597.  
  598. 7.3:    How can I discover how many arguments a function was actually
  599.     called with?
  600.  
  601. A:    Any function which takes a variable number of arguments must be
  602.     able to determine from the arguments themselves how many of them
  603.     there are.
  604.  
  605. 7.4:    I can't get the va_arg macro to pull in an argument of type
  606.     pointer-to-function.
  607.  
  608. A:    Use a typedef.
  609.  
  610. 7.5:    How can I write a function which takes a variable number of
  611.     arguments and passes them to some other function (which takes a
  612.     variable number of arguments)?
  613.  
  614. A:    In general, you cannot.
  615.  
  616. 7.6:    How can I call a function with an argument list built up at run
  617.     time?
  618.  
  619. A:    You can't.
  620.  
  621.  
  622. Section 8. Boolean Expressions and Variables
  623.  
  624. 8.1:    What is the right type to use for boolean values in C?  Why
  625.     isn't it a standard type?  Should #defines or enums be used for
  626.     the true and false values?
  627.  
  628. A:    C does not provide a standard boolean type, because picking one
  629.     involves a space/time tradeoff which is best decided by the
  630.     programmer.  The choice between #defines and enums is arbitrary
  631.     and not terribly interesting.
  632.  
  633. 8.2:    What if a built-in boolean or relational operator "returns"
  634.     something other than 1?
  635.  
  636. A:    When a boolean value is generated by a built-in operator, it is
  637.     guaranteed to be 1 or 0.  (This is _not_ true for some library
  638.     routines such as isalpha.)
  639.  
  640.  
  641. Section 9. Structs, Enums, and Unions
  642.  
  643. 9.1:    What is the difference between an enum and a series of
  644.     preprocessor #defines?
  645.  
  646. A:    At the present time, there is little difference.  The ANSI
  647.     standard states that enumerations are compatible with integral
  648.     types.
  649.  
  650. 9.2:    I heard that structures could be assigned to variables and
  651.     passed to and from functions, but K&R I says not.
  652.  
  653. A:    These operations are supported by all modern compilers.
  654.  
  655. 9.3:    How does struct passing and returning work?
  656.  
  657. A:    If you really need to know, see the unabridged list.
  658.  
  659. 9.4:    I have a program which works correctly, but dumps core after it
  660.     finishes.  Why?
  661.  
  662. A:    Check to see if a structure type declaration just before main is
  663.     missing its trailing semicolon, causing the compiler to believe
  664.     that main returns a structure.  See also question 17.21.
  665.  
  666. 9.5:    Why can't you compare structs?
  667.  
  668. A:    There is no reasonable way for a compiler to implement struct
  669.     comparison which is consistent with C's low-level flavor.
  670.  
  671. 9.6:    How can I read/write structs from/to data files?
  672.  
  673. A:    It is relatively straightforward to use fread and fwrite.
  674.  
  675. 9.7:    I came across some code that declared a structure with the last
  676.     member an array of one element, and then did some tricky
  677.     allocation to make the array act like it had several elements.
  678.     Is this legal and/or portable?
  679.  
  680. A:    An ANSI Interpretation Ruling has deemed it to be not strictly
  681.     conforming.
  682.  
  683. 9.8:    How can I determine the byte offset of a field within a
  684.     structure?
  685.  
  686. A:    ANSI C defines the offsetof macro, which should be used if
  687.     available.
  688.  
  689. 9.9:    How can I access structure fields by name at run time?
  690.  
  691. A:    Build a table of names and offsets, using the offsetof() macro.
  692.  
  693. 9.10:    Why does sizeof report a larger size than I expect for a
  694.     structure type, as if there was padding at the end?
  695.  
  696. A:    The alignment of arrays of structures must be preserved.
  697.  
  698. 9.11:    How can I turn off structure padding?
  699.  
  700. A:    There is no standard method.
  701.  
  702. 9.12:    Can I initialize unions?
  703.  
  704. A:    ANSI Standard C allows an initializer for the first member.
  705.  
  706. 9.13:    Can I pass constant values to routines which accept struct
  707.     arguments?
  708.  
  709. A:    No.  C has no way of generating anonymous struct values.
  710.  
  711.  
  712. Section 10. Declarations
  713.  
  714. 10.1:    How do you decide which integer type to use?
  715.  
  716. A:    If you might need large values, use long.  Otherwise, if space
  717.     is very important, use short.  Otherwise, use int.
  718.  
  719. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  720.  
  721. A:    There are arguments in favor of long int and long long int,
  722.     among other options.
  723.  
  724. 10.3:    I can't seem to define a linked list node which contains a
  725.     pointer to itself.
  726.  
  727. A:    Structs in C can certainly contain pointers to themselves; the
  728.     discussion and example in section 6.5 of K&R make this clear.
  729.     Problems arise if an attempt is made to define (and use) a
  730.     typedef in the midst of such a declaration; avoid this.
  731.  
  732. 10.4:    How do I declare an array of N pointers to functions returning
  733.     pointers to functions returning pointers to characters?
  734.  
  735. A:    char *(*(*a[N])())();
  736.     Using a chain of typedefs, or the cdecl program, makes these
  737.     declarations easier.
  738.  
  739. 10.5:    How can I declare a function that returns a pointer to a
  740.     function of its own type?
  741.  
  742. A:    You can't do it directly.  Use a cast, or wrap a struct around
  743.     the pointer and return that.
  744.  
  745. 10.6:    My compiler is complaining about an invalid redeclaration of a
  746.     function, but I only define it once and call it once.
  747.  
  748. A:    Non-int functions must be declared before they are called.
  749.  
  750. 10.7:    What's the best way to declare and define global variables?
  751.  
  752. A:    It is best to place the definition in some central .c file, with
  753.     an external declaration in a header file.
  754.  
  755. 10.8:    What does extern mean in a function declaration?
  756.  
  757. A:    Nothing, really.
  758.  
  759. 10.9:    How do I initialize a pointer to a function?
  760.  
  761. A:    Use something like "extern int func(); int (*fp)() = func; " .
  762.  
  763. 10.10:    I've seen different methods used for calling through pointers to
  764.     functions.
  765.  
  766. A:    The extra parentheses and explicit * are now officially
  767.     optional, although some older implementations require them.
  768.  
  769. 10.11:    What's the auto keyword good for?
  770.  
  771. A:    Nothing.
  772.  
  773.  
  774. Section 11. Stdio
  775.  
  776. 11.1:    Why doesn't the code "char c; while((c = getchar()) != EOF)..."
  777.     work?
  778.  
  779. A:    The variable to hold getchar's return value must be an int.
  780.  
  781. 11.2:    Why doesn't the code scanf("%d", i); work?
  782.  
  783. A:    scanf needs pointers to the variables it is to fill in.
  784.  
  785. 11.3:    Why doesn't the code double d; scanf("%f", &d); work?
  786.  
  787. A:    Unlike printf, scanf uses %lf for double, and %f for float.
  788.  
  789. 11.4:    Why won't the code "while(!feof(infp)) {
  790.     fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work?
  791.  
  792. A:    EOF is only indicated _after_ an input routine has reached end-
  793.     of-file.
  794.  
  795. 11.5:    Why does everyone say not to use gets()?
  796.  
  797. A:    It cannot be prevented from overflowing the input buffer.
  798.  
  799. 11.6:    Why does errno contain ENOTTY after a call to printf?
  800.  
  801. A:    Don't worry about it.  It is only meaningful for a program to
  802.     inspect the contents of errno after an error has occurred.
  803.  
  804. 11.7:    My program's prompts and intermediate output don't always show
  805.     up on the screen, especially when I pipe the output through
  806.     another program.
  807.  
  808. A:    It is best to use an explicit fflush(stdout) whenever output
  809.     should definitely be visible.
  810.  
  811. 11.8:    When I read from the keyboard with scanf, it seems to hang until
  812.     I type one extra line of input.
  813.  
  814. A:    scanf was designed for free-format input, which is seldom what
  815.     you want when reading from the keyboard.
  816.  
  817. 11.9:    I'm trying to update a file in place, by using fopen mode "r+",
  818.     but it's not working.
  819.  
  820. A:    Be sure to call fseek between reading and writing.
  821.  
  822. 11.10:    How can I read one character at a time, without waiting for the
  823.     RETURN key?
  824.  
  825. A:    See question 16.1.
  826.  
  827. 11.11:    Will fflush(stdin) flush unread characters from the standard
  828.     input stream?
  829.  
  830. A:    No.
  831.  
  832. 11.12:    How can I redirect stdin or stdout from within a program?
  833.  
  834. A:    Use freopen.
  835.  
  836. 11.13:    Once I've used freopen, how can I get the original stdout back?
  837.  
  838. A:    It's not easy.  Try avoiding freopen.
  839.  
  840. 11.14:    How can I recover the file name given an open file descriptor?
  841.  
  842. A:    This problem is, in general, insoluble.  It is best to remember
  843.     the names of files yourself when you open them.
  844.  
  845.  
  846. Section 12. Library Subroutines
  847.  
  848. 12.1:    Why does strncpy not always write a '\0'?
  849.  
  850. A:    For mildly-interesting historical reasons.
  851.  
  852. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  853.     as the comparison function, but it's not working.
  854.  
  855. A:    You'll have to write a "helper" comparison function which takes
  856.     two generic pointer arguments, converts them to char **, and
  857.     dereferences them, yielding char *'s which can be usefully
  858.     compared.
  859.  
  860. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  861.     comparison routine takes pointers to structures, but the
  862.     compiler complains that the function is of the wrong type for
  863.     qsort.  How can I cast the function pointer to shut off the
  864.     warning?
  865.  
  866. A:    The conversions must be in the comparison function, which must
  867.     be declared as accepting "generic pointers" (const void * or
  868.     char *).
  869.  
  870. 12.4:    How can I convert numbers to strings?
  871.  
  872. A:    Just use sprintf.
  873.  
  874. 12.5:    How can I get the time of day in a C program?
  875.  
  876. A:    Just use the time, ctime, and/or localtime functions.
  877.  
  878. 12.6:    How can I convert a struct tm or a string into a time_t?
  879.  
  880. A:    The ANSI mktime routine converts a struct tm to a time_t.  No
  881.     standard routine exists to parse strings.
  882.  
  883. 12.7:    How can I perform calendar manipulations?
  884.  
  885. A:    The ANSI/ISO Standard C mktime and difftime functions provide
  886.     support for both problems.
  887.  
  888. 12.8:    I need a random number generator.
  889.  
  890. A:    The standard C library has one: rand().
  891.  
  892. 12.9:    How can I get random integers in a certain range?
  893.  
  894. A:    One method is something like
  895.  
  896.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  897.  
  898. 12.10:    Each time I run my program, I get the same sequence of numbers
  899.     back from rand().
  900.  
  901. A:    You can call srand() to seed the pseudo-random number generator
  902.     with a more random initial value.
  903.  
  904. 12.11:    I need a random true/false value, so I'm taking rand() % 2, but
  905.     it's just alternating 0, 1, 0, 1, 0...
  906.  
  907. A:    Try using the higher-order bits.
  908.  
  909. 12.12:    I'm trying to port this old program.  Why do I get "undefined
  910.     external" errors for some library routines?
  911.  
  912. A:    Some semistandard routines have been renamed or replaced over
  913.     the years; see the full list for details.
  914.  
  915. 12.13:    I get errors due to library routines being undefined even though
  916.     I #include the right header files.
  917.  
  918. A:    You may have to explicitly ask for the correct libraries to be
  919.     searched.
  920.  
  921. 12.14:    I'm still getting errors due to library routines being
  922.     undefined, even though I'm requesting the right libraries.
  923.  
  924. A:    Library search order is significant; usually, you must search
  925.     the libraries last.
  926.  
  927. 12.15:    I need some code to do regular expression matching.
  928.  
  929. A:    regexp libraries abound; see the full list for details.
  930.  
  931. 12.16:    How can I split up a string into whitespace-separated arguments?
  932.  
  933. A:    Try strtok.
  934.  
  935.  
  936. Section 13. Lint
  937.  
  938. 13.1:    I just typed in this program, and it's acting strangely.  Can
  939.     you see anything wrong with it?
  940.  
  941. A:    Try running lint first.
  942.  
  943. 13.2:    How can I shut off the "warning: possible pointer alignment
  944.     problem" message lint gives me for each call to malloc?
  945.  
  946. A:    It may be easier simply to ignore the message, perhaps in an
  947.     automated way with grep -v.
  948.  
  949. 13.3:    Where can I get an ANSI-compatible lint?
  950.  
  951. A:    See the unabridged list for two commercial products.
  952.  
  953.  
  954. Section 14. Style
  955.  
  956. 14.1:    Is the code "if(!strcmp(s1, s2))" good style?
  957.  
  958. A:    Not particularly.
  959.  
  960. 14.2:    What's the best style for code layout in C?
  961.  
  962. A:    There is no one "best style," but see the full list for a few
  963.     suggestions.
  964.  
  965. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  966.     standards?
  967.  
  968. A:    See the unabridged list.
  969.  
  970.  
  971. Section 15. Floating Point
  972.  
  973. 15.1:    My floating-point calculations are acting strangely and giving
  974.     me different answers on different machines.
  975.  
  976. A:    First, make sure that you have #included <math.h>, and correctly
  977.     declared other functions returning double.  If the problem isn't
  978.     that simple, see the full list for a brief explanation, or any
  979.     good programming book for a better one.
  980.  
  981. 15.2:    I keep getting "undefined: _sin" compilation errors.
  982.  
  983. A:    Make sure you're linking with the correct math library.
  984.  
  985. 15.3:    Where is C's exponentiation operator?
  986.  
  987. A:    Try using the pow() function.
  988.  
  989. 15.4:    How do I round numbers?
  990.  
  991. A:    The simplest way is with code like (int)(x + 0.5) .
  992.  
  993. 15.5:    How do I test for IEEE NaN and other special values?
  994.  
  995. A:    There is not yet a portable way, but see the full list for
  996.     ideas.
  997.  
  998. 15.6:    I'm having trouble with a Turbo C program which crashes and says
  999.     something like "floating point formats not linked."
  1000.  
  1001. A:    Some compilers for small machines, including Turbo C, attempt to
  1002.     leave out floating point support if it looks like it will not be
  1003.     needed.  The programmer must occasionally insert an extra,
  1004.     explicit call to a floating-point library routine to force
  1005.     loading of floating-point support.
  1006.  
  1007.  
  1008. Section 16. System Dependencies
  1009.  
  1010. 16.1:    How can I read a single character from the keyboard without
  1011.     waiting for a newline?
  1012.  
  1013. A:    Contrary to popular belief and many people's wishes, this is not
  1014.     a C-related question.  How to do so is a function of the
  1015.     operating system in use.
  1016.  
  1017. 16.2:    How can I find out if there are characters available for reading
  1018.     (and if so, how many)?  Alternatively, how can I do a read that
  1019.     will not block if there are no characters available?
  1020.  
  1021. A:    These, too, are entirely operating-system-specific.
  1022.  
  1023. 16.3:    How can I clear the screen?
  1024.  
  1025. A:    Such things depend on the output device you're using.
  1026.  
  1027. 16.4:    How do I read the mouse?
  1028.  
  1029. A:    What system are you using?
  1030.  
  1031. 16.5:    How can my program discover the complete pathname to the
  1032.     executable file from which it was invoked?
  1033.  
  1034. A:    argv[0] may contain all or part of the pathname.  You may be
  1035.     able to duplicate the command language interpreter's search path
  1036.     logic to locate the executable.
  1037.  
  1038. 16.6:    How can a process change an environment variable in its caller?
  1039.  
  1040. A:    In general, it cannot.
  1041.  
  1042. 16.7:    How can I check whether a file exists?
  1043.  
  1044. A:    You can try the access() routine.
  1045.  
  1046. 16.8:    How can I find out the size of a file, prior to reading it in?
  1047.  
  1048. A:    You might be able to get an estimate using stat() or
  1049.     fseek/ftell.
  1050.  
  1051. 16.9:    How can a file be shortened in-place without completely clearing
  1052.     or rewriting it?
  1053.  
  1054. A:    There are various ways to do this, but there is no truly
  1055.     portable solution.
  1056.  
  1057. 16.10:    How can I implement a delay, or time a user's response, with
  1058.     sub-second resolution?
  1059.  
  1060. A:    Unfortunately, there is no portable way.
  1061.  
  1062. 16.11:    How can I read in an object file and jump to routines in it?
  1063.  
  1064. A:    You want a dynamic linker and/or loader.
  1065.  
  1066. 16.12:    How can I invoke an operating system command from within a
  1067.     program?
  1068.  
  1069. A:    Use system().
  1070.  
  1071. 16.13:    How can I invoke an operating system command and trap its
  1072.     output?
  1073.  
  1074. A:    Unix and some other systems provide a popen() routine.
  1075.  
  1076. 16.14:    How can I read a directory in a C program?
  1077.  
  1078. A:    See if you can use the opendir() and readdir() routines.
  1079.  
  1080. 16.15:    How can I do serial ("comm") port I/O?
  1081.  
  1082. A:    It's system-dependent.
  1083.  
  1084.  
  1085. Section 17. Miscellaneous
  1086.  
  1087. 17.1:    What can I safely assume about the initial values of variables
  1088.     which are not explicitly initialized?
  1089.  
  1090. A:    Variables with "static" duration start out as 0, as if the
  1091.     programmer had initialized them.  Variables with "automatic"
  1092.     duration, and dynamically-allocated memory, start out containing
  1093.     garbage (with the exception of calloc).
  1094.  
  1095. 17.2:    What's wrong with
  1096.  
  1097.         f() { char a[] = "Hello, world!"; }
  1098.  
  1099. A:    Perhaps you have a pre-ANSI compiler.
  1100.  
  1101. 17.3:    How can I write data files which can be read on other machines
  1102.     with different data formats?
  1103.  
  1104. A:    The best solution is to use text files.
  1105.  
  1106. 17.4:    How can I delete a line from the middle of a file?
  1107.  
  1108. A:    Short of rewriting the file, you probably can't.
  1109.  
  1110. 17.5:    How can I return several values from a function?
  1111.  
  1112. A:    Either pass pointers to locations which the function can fill
  1113.     in, or have the function return a structure containing the
  1114.     desired values.
  1115.  
  1116. 17.6:    How can I call a function, given its name as a string?
  1117.  
  1118. A:    The most straightforward thing to do is maintain a
  1119.     correspondence table of names and function pointers.
  1120.  
  1121. 17.7:    I seem to be missing the system header file <sgtty.h>.  Can
  1122.     someone send me a copy?
  1123.  
  1124. A:    You cannot just pick up a copy of someone else's header file and
  1125.     expect it to work, since the definitions within header files are
  1126.     frequently system-dependent.  Contact your vendor.
  1127.  
  1128. 17.8:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  1129.     from C?
  1130.  
  1131. A:    The answer is entirely dependent on the machine and the specific
  1132.     calling sequences of the various compilers in use.
  1133.  
  1134. 17.9:    Does anyone know of a program for converting Pascal or FORTRAN
  1135.     to C?
  1136.  
  1137. A:    Several public-domain programs are available, namely ptoc, p2c,
  1138.     and f2c.  See the full list for details.
  1139.  
  1140. 17.10:    Can I use a C++ compiler to compile C code?
  1141.  
  1142. A:    Not necessarily; C++ is not a strict superset of C.
  1143.  
  1144. 17.11:    I'm looking for C development tools (cross-reference generators,
  1145.     code beautifiers, etc.).
  1146.  
  1147. A:    See the full list for a few names.
  1148.  
  1149. 17.12:    Where can I get copies of all these public-domain programs?
  1150.  
  1151. A:    See the regular postings in the comp.sources.unix and
  1152.     comp.sources.misc newsgroups for information.
  1153.  
  1154. 17.13:    When will the next Obfuscated C Code Contest be held?  How can I
  1155.     get a copy of the previous winning entries?
  1156.  
  1157. A:    See the full list, or send e-mail to judges@toad.com .
  1158.  
  1159. 17.14:    Why don't C comments nest?  Are they legal inside quoted
  1160.     strings?
  1161.  
  1162. A:    Nested comments would cause more harm than good.  The character
  1163.     sequences /* and */ are not special within double-quoted
  1164.     strings.
  1165.  
  1166. 17.15:    How can I get the ASCII value corresponding to a character?
  1167.  
  1168. A:    In C, if you have the character, you have its value.
  1169.  
  1170. 17.16:    How can I implement sets and/or arrays of bits?
  1171.  
  1172. A:    Use arrays of char or int, with a few macros to access the right
  1173.     bit at the right index.
  1174.  
  1175. 17.17:    What is the most efficient way to count the number of bits which
  1176.     are set in a value?
  1177.  
  1178. A:    This and many other similar bit-twiddling problems can often be
  1179.     sped up and streamlined using lookup tables.
  1180.  
  1181. 17.18:    How can I make this code more efficient?
  1182.  
  1183. A:    Efficiency is not important nearly as often as people tend to
  1184.     think it is.  Most of the time, by simply paying attention to
  1185.     good algorithm choices, perfectly acceptable results can be
  1186.     achieved.
  1187.  
  1188. 17.19:    Are pointers really faster than arrays?  How much do function
  1189.     calls slow things down?
  1190.  
  1191. A:    Precise answers to these and many similar questions depend of
  1192.     course on the processor and compiler in use.
  1193.  
  1194. 17.20:    Why does the code "char *p = "Hello, world!";
  1195.     p[0] = tolower(p[0]);" crash?
  1196.  
  1197. A:    String literals are not modifiable, except (in effect) when they
  1198.     are used as array initializers.
  1199.  
  1200. 17.21:    This program crashes before it even runs!
  1201.  
  1202. A:    Look for very large, local arrays.
  1203.     (See also question 9.4.)
  1204.  
  1205. 17.22:    What does "Segmentation violation" mean?
  1206.  
  1207. A:    It generally means that your program tried to access memory it
  1208.     shouldn't have.
  1209.  
  1210. 17.23:    My program is crashing, apparently somewhere down inside malloc.
  1211.  
  1212. A:    Make sure you aren't using more memory than you malloc'ed,
  1213.     especially for strings (which need strlen() + 1 bytes).
  1214.  
  1215. 17.24:    Does anyone have a C compiler test suite I can use?
  1216.  
  1217. A:    See the full list for several sources.
  1218.  
  1219. 17.25:    Where can I get a YACC grammar for C?
  1220.  
  1221. A:    See the ANSI Standard, or the unabridged list.
  1222.  
  1223. 17.26:    I need code to parse and evaluate expressions.
  1224.  
  1225. A:    Two available packages are mentioned in the full list.
  1226.  
  1227. 17.27:    I need to compare two strings for close, but not necessarily
  1228.     exact, equality.
  1229.  
  1230. A:    The traditional routine for doing this sort of thing involves
  1231.     the "soundex" algorithm.
  1232.  
  1233. 17.28:    How can I find the day of the week given the date?
  1234.  
  1235. A:    Use Zeller's congruence.
  1236.  
  1237. 17.29:    Will 2000 be a leap year?
  1238.  
  1239. A:    Yes.
  1240.  
  1241. 17.30:    How do you pronounce "char"?
  1242.  
  1243. A:    Like the English words "char," "care," or "car" (your choice).
  1244.  
  1245. 17.31:    What's a good book for learning C?
  1246.  
  1247. A:    There are far too many to list here; the full list contains a
  1248.     few pointers.
  1249.  
  1250. 17.32:    Are there any C tutorials on the net?
  1251.  
  1252. A:    There are at least two of them.
  1253.  
  1254. 17.33:    Where can I get extra copies of this list?
  1255.  
  1256. A:    For now, just pull it off the net; the unabridged version is
  1257.     normally posted on the first of each month, with an Expires:
  1258.     line which should keep it around all month.  It can also be
  1259.     found in the newsgroups comp.answers and news.answers .  Several
  1260.     sites archive news.answers postings and other FAQ lists,
  1261.     including this one: two sites are rtfm.mit.edu (directory
  1262.     pub/usenet), and ftp.uu.net (directory usenet).  The archie
  1263.     server should help you find others.
  1264.  
  1265.                     Steve Summit
  1266.                     scs@eskimo.com
  1267.  
  1268. This article is Copyright 1988, 1990-1994 by Steve Summit.
  1269. It may be freely redistributed so long as the author's name, and this
  1270. notice, are retained.
  1271.